from PIL import Image, ImageDraw, ImageFont
import os
import numpy as np
import json
from .send_to import send_str_ls
from bdtime import tt
from warnings import warn


output_dir = 'tempdir/text'
os.makedirs(output_dir, exist_ok=True)


image_dir = 'data/images'


def read_str_ls(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        ss = f.read()
    str_ls = [list(s) for s in ss.split('\n')]
    return str_ls


import re


def has_chinese(text):
    pattern = re.compile('[\u4e00-\u9fa5]')
    return bool(pattern.search(text))


def text_to_image(text=None, font_path=None, auto_width=False, font_size=10, threshold=175, output_file=None, image_path=None, use_cache=True):
    threshold = int(threshold)
    if text is None and image_path:
        text = os.path.basename(image_path)
    assert text, '`text`和`image_path`不能全为空!'
    output_file = output_file if output_file else os.path.join(output_dir, f"{text}_{auto_width}_{font_size}_{threshold}.txt")

    os.makedirs(output_dir, exist_ok=True)

    if use_cache and os.path.exists(output_file):
        str_ls = read_str_ls(file_path=output_file)
    else:
        # print(f'--- create pixel text: {output_file}')
        if image_path is None:
            img_width = len(text) * font_size if auto_width else font_size

            # 创建一个白色背景的图像
            # image_size = (img_width, max(font_size - move_top, 0))
            image_size = (img_width, font_size)
            image = Image.new("RGB", image_size, "white")
            draw = ImageDraw.Draw(image)

            chinese_font_path = "C:\\Windows\\Fonts\\simhei.ttf"  # 替换为实际的中文字体文件路径
            if font_path is None:
                font_path = chinese_font_path

            assert os.path.exists(font_path)

            # 使用指定的中文字体
            font = ImageFont.truetype(font_path, font_size)

            xy = (0, 0)
            if len(text) == 1 and not has_chinese(text):
                xy = (image_size[0] / 4, 0)
            # 将文本绘制到图像上
            draw.text(xy, text, font=font, fill="black")
        else:
            if not os.path.isabs(image_path) and not image_path.startswith('data'):
                image_path = os.path.join(image_dir, image_path)
            image = Image.open(image_path)
            image = image.resize((font_size, font_size))

        gray_image = image.convert("L")
        # 转为NumPy数组
        gray_array = np.array(gray_image)

        binary_array = (gray_array <= threshold).astype(np.uint8)
        str_ls = show_binary_array(binary_array, ignore_empty_row=False, show=False)

        ss = conv_str_ls_to_ss(str_ls)

        try:
            with open(output_file, 'w+', encoding='utf-8') as f:
                f.write(ss)
        except Exception as e:
            warn(str(e))

    show_str_ls(str_ls)

    return str_ls, output_file


def conv_str_ls_to_ss(str_ls):
    ss = '\n'.join([''.join(ls) for ls in str_ls])
    return ss


def show_binary_array(binary_array, ignore_empty_row=False, show=True):
    str_ls = []
    vs = ['□', '■']
    for r in binary_array:
        if ignore_empty_row and sum(r) == 0:
            continue

        ls = []
        for c in r:
            ls.append(vs[c])
        str_ls.append(ls)
    # res = str_ls[ignore_row:-ignore_row] if ignore_row else str_ls

    if show:
        show_str_ls(str_ls)
    return str_ls


def show_str_ls(str_ls):
    for ls in str_ls:
        for o in ls:
            print(o, end=' ')
        print()


def call_output(str_ls):
    print(123123)


def send_msg(input_text, image_path, send_all, font_size, threshold=None, only_debug=True):
    if not threshold:
        # threshold = 254 if image_path else 175
        threshold = 205 if image_path else 175

    if image_path:
        str_ls, _ = text_to_image(image_path=image_path, font_size=font_size, threshold=threshold)
        # show_str_ls(str_ls)
    else:
        out_ls = []
        for it in input_text:
            if not it:
                continue

            str_ls, _ = text_to_image(it, font_size=font_size, threshold=threshold)
            out_ls.append(str_ls)

    if not only_debug:
        if image_path:
            # str_ls, _ = text_to_image(image_path=image_path, font_size=16, threshold=254)
            send_str_ls(str_ls)
        else:
            for str_ls in out_ls:
                if tt.stop_alt():
                    break
                send_str_ls(str_ls, send_all=send_all, interval_1=0.5, interval_2=0.1, interval_3=0.2)


def main():
    # input_text = "Hello, Text to Image!"
    # input_text = "你家炸了"
    # input_text = "要翻盘"
    # input_text = "你家炸了! 听得到么? 你家炸了!!"
    # input_text = "20投"
    # input_text = "家炸了"
    # input_text = "不行"
    # input_text = "可恶"
    # input_text = "骗子"
    # input_text = "怕怕"
    # input_text = "急了"
    # input_text = "点"
    # input_text = "加油    "
    # input_text = "体面点"

    # input_text = ["操", "你", "妈"]
    input_text = ["草", "你", "妈"]
    # input_text = ['速', '度']
    # input_text = ['废', '物']
    # input_text = ["点"]
    # input_text = ["该", "点", "了"]
    # input_text = ["GG"]
    # input_text = ["GG"]
    # input_text = ['我', '最', '帅']
    # input_text = ["20", "投"]
    # input_text = ["垃", "圾"]
    # input_text = ["草"]
    input_text = ["干"]
    # input_text = "点"
    # input_text = "帅"
    # input_text = "狗"
    # input_text = ["2B"]
    # input_text = ["20"]
    # input_text = ["15"]

    image_path = None

    # image_path = os.path.join(image_dir, '笑脸.png')
    # image_path = os.path.join(image_dir, '不开心.png')
    # image_path = os.path.join(image_dir, '中指.png')
    # image_path = os.path.join(image_dir, 'QQ.png')


    send_all = True
    # send_all = False

    # only_debug = True
    only_debug = False

    interval_0 = 1
    tt.sleep(interval_0)

    font_size = 11 if send_all else 14

    if image_path:
        str_ls, _ = text_to_image(image_path=image_path, font_size=font_size, threshold=205)
        # show_str_ls(str_ls)
    else:
        out_ls = []
        for it in input_text:
            if not it:
                continue

            str_ls, _ = text_to_image(it, font_size=font_size)

            # str_ls = text_to_image(it, font_size=12)
            # str_ls = text_to_image(it, font_size=10)
            # str_ls = text_to_image(it, font_size=16)
            # str_ls = text_to_image(it, font_size=22)
            # str_ls = text_to_image(it, font_size=10, threshold=175)
            # str_ls = text_to_image(it, font_size=13, threshold=200)
            # str_ls = text_to_image(it, font_size=12, threshold=128)
            # text_to_image(it, font_size=16, threshold=250)
            out_ls.append(str_ls)

    if not only_debug:
        if image_path:
            # str_ls, _ = text_to_image(image_path=image_path, font_size=16, threshold=254)
            send_str_ls(str_ls)
        else:
            for str_ls in out_ls:
                if tt.stop_alt():
                    break
                send_str_ls(str_ls, send_all=send_all, interval_1=0.5, interval_2=0.1, interval_3=0.2)


if __name__ == "__main__":
    main()

